package other.juc;

import sun.misc.Unsafe;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CountDownLatch countDownLatch = new CountDownLatch(1);

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //开始执行任务
                    Thread.sleep(3000); //模拟任务执行时间
                    countDownLatch.countDown(); //任务执行结束后，计数器减一
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //阻塞main线程，当任务执行结束调用countDown方法使计数器归零后，唤醒主线程
        countDownLatch.await();
        executorService.shutdown();
    }


    private volatile int state = 0;
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static long stateOffset;  //获取成员变量的偏移量

    static {
        try {
            stateOffset = unsafe.objectFieldOffset(Main.class.getDeclaredField("state"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
    public void doSomething(){
        /**
         * compareAndSwapInt的四个参数
         * parma1：当前实例对象
         * parma2：成员变量在内存地址中的偏移量
         * parma3：预期值
         * parma4：期望更改值
        */
        if(unsafe.compareAndSwapInt(this,stateOffset,0,1)){
            state = 1;
        }
    }

    public static synchronized void lock1(){
        //线程获取到了lock1中的synchronized锁
        //再次调用另外一个加同步锁的lock2方法
        lock2();
    }
    public static synchronized void lock2(){

    }
}
